package czk.concrent.juc.AQS;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 自定义锁和自定义同步器类
 * 不可重入锁
 * @Author:ChenZhangKun
 * @Date: 2020/7/11 18:52
 */
public class AqsTest {
    public static void main(String[] args) {
        MyLock myLock=new MyLock();
        new Thread(()->{
            try {
                myLock.lock();
                System.out.println("1加锁成功");
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                myLock.unlock();
                System.out.println("1解锁成功");
            }
        }).start();
        new Thread(()->{
            try {

                myLock.lock();
                System.out.println("2加锁成功");
            }finally {
                myLock.unlock();
                System.out.println("2解锁成功");
            }
        }).start();
    }
}
class MyLock implements Lock{
    // AbstractQueuedSynchronizer实现了大部分锁得的方法
    // 独占锁
    class MySync extends AbstractQueuedSynchronizer{
        @Override
        protected boolean tryAcquire(int arg) {
            if (compareAndSetState(0,1)){
                // 加上锁
                // 设置为持有锁的线程
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            setExclusiveOwnerThread(null);
            // 设置为0表示没有加上锁
            // 注意顺序，读写屏障
            setState(0);
            return true;
        }
        // 是否持有独占锁
        @Override
        protected boolean isHeldExclusively() {
           return getState()==1;
        }
        public Condition newCondition(){
            return new ConditionObject();
        }
    }
   MySync mySync=new MySync();

    // 加锁
    @Override
    public void lock() {
        mySync.acquire(1);
    }
    // 可打断加锁
    @Override
    public void lockInterruptibly() throws InterruptedException {
        mySync.acquireInterruptibly(1);
    }
    // 尝试加锁
    @Override
    public boolean tryLock() {

        return mySync.tryAcquire(1);
    }
    // 尝试加锁不成功后，加入队列等待
    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return mySync.tryAcquireNanos(1,unit.toNanos(time));
    }
    // 解锁
    @Override
    public void unlock() {
        mySync.release(1);
    }
    // 创建休息室
    @Override
    public Condition newCondition() {
        return mySync.newCondition();
    }
}
